<?php
namespace control;
/*
*培训计划类
*/

class trainingPlanClass extends adIndexClass
{
    private const page = 'trainingPlan';
    private const table = 'training_plan';
    private const tableMx = 'training_plan_detail';
    private const title = '培训计划';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => L('recruitment.table.orderNo'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => L('trainingPlan.table.planName'),
                        'width' => 250,
                    ],
                    'planStartAndEnd'  => [
                        'name'  => L('trainingPlan.table.planStartAndEnd'),
                        'width' => 350
                    ],
                    'deptName'         => [
                        'name'  => L('recruitment.table.staffDept'),
                        'width' => 200,
                    ],
                    'prepared'          => [
                        'name'  => L('recruitment.table.prepared'),
                        'width' => 200,
                    ],
                    'time'    => [
                        'name'  => L('recruitment.table.createTime'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'        => [
                        'name'  => L('trainingPlan.table.state'),
                        'width' => 200,
                    ],
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('recruitment.table.orderNo') => text(array("name" => "orderNo")),
                    L('trainingPlan.table.planName')     => text(array("name" => "name")),
                    L('recruitment.table.prepared') => selectMultiple(array("name" => "stid", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid', 'class' => 'width200')),
                ],
                [
                    L('recruitment.table.createTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    L('trainingPlan.table.state') => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $url = root . "control/adIndex.html?cla=" . self::page;
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>" . L('recruitment.table.add') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('recruitment.table.del') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
            "name" => $this->post('name'),//计划名称
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "stid" => $this->post('stid'),//申请人
        );
        $and = $this->seeSelf(self::page, 'stid');
        if ($this->post('createTime')) {
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and date(time) >='{$timeArr[0]}' and  date(time) <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('trainingPlan.table.plan'), "click" => "newIframe('" . L('trainingPlan.table.plan') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "planStartAndEnd":
                        $row[] = $array['startDate'] . ' ~ ' . $array['endDate'];
                        break;
                    case "prepared":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('trainingPlan.table.planName')."：" => text(array('name' => 'name', 'value' => $info['name'])),
                    must . L('trainingPlan.table.planStartAndEnd')."：" => text(["name" => "chooseDate", 'class' => 'select', 'laydate' => ['range' => '~'], "value" => $info['id'] ? ($info['startDate'] . ' ~ ' . $info['endDate']) : '']),
                ],
                [
                    L('staffProfiles.table.text')."：" => textarea(["name" => "text", "value" => $info['text']])
                        . hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor'), "height" => 250, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $timeArr = $this->post('chooseDate') ? explode(' ~ ', $this->post('chooseDate')) : [];
        $field = [
            'name' => $this->post('name'),
            'startDate' => $timeArr[0],
            'endDate' => $timeArr[1],
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'name' => L('trainingPlan.table.planName'),
            'startDate' => L('trainingPlan.table.planStartAndEnd'),
            'endDate' => L('trainingPlan.table.planStartAndEnd'),
        ];
        $rules = [
            'name' => 'required',
            'startDate' => 'required',
            'endDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('trainingPlan.table.edit_permission');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $userNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'PXJH' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'deptName' => $department['name'],
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{name}}','{{id}}'],[$this->control['name'],$field['name'],$id],L('trainingPlan.table.plan_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*数据导入分析*/
    public function import()
    {
        $templateId = $this->post('templateId');
        $id = $_SESSION[self::page]['id'];
        $info = query(self::table, " id = '$id'");
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = L('staffProfiles.tip.permission_import_warn');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('trainingPlan.table.no_plan');
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $field = [
                        'id' => self::getId(),
                        'orderId' => $info['id'],
                        'time' => $this->time,
                        'type' => $cell['培训类别'],
                        'project' => $cell['培训项目'],
                        'trainingTime' => $cell['培训时间'],
                        'hour' => $cell['培训课时'],
                        'budget' => $cell['预算'],
                        'department' => $cell['主讲部门'],
                        'trainingObject' => $cell['培训对象'],
                    ];
                    $annotation = [
                        'type' => L('trainingPlan.table.trainingType'),
                        'project' => L('trainingPlan.table.trainingProject'),
                        'trainingTime' => L('trainingPlan.table.trainingTime'),
                        'hour' => L('trainingPlan.table.hours'),
                    ];
                    $rules = [
                        'type' => 'required',
                        'project' => 'required',
                        'trainingTime' => 'required',
                        'hour' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $line = str_replace(['{{i}}'], [$row_list], L('job.other.line'));
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= $line."：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } else {
                        $warn = insert(["table" => self::tableMx, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= $line."：".L('job.other.import_success')."<br>";
                        } else {
                            $text .= $line."：".L('job.other.import_failed')."<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text =str_replace(['{{staffName}}','{{fileName}}'],[$this->control['name'],$_FILES['file']['name']],L('job.other.import_log'))  .  '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        resp:
        return json_encode($json,320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] =  L('staffProfiles.tip.permission_export_warn');
        }  else {
            $data = [];
            $id = $_SESSION[self::page]['id'];
            $info = query(self::table, " id = '$id'");
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }

            if (!self::is_null_array($checkedId)){
                $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' and id in ('".implode("','", $checkedId)."')  order by time asc"))['array'];
            }else{
                $result = find(array('table' => self::tableMx, 'where' => "orderId = '$id' order by time asc"))['array'];
            }
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '培训类别'=>$array['type'],
                            '培训项目'=>$array['project'],
                            '培训时间'=>$array['trainingTime'],
                            '培训课时'=>$array['hour'],
                            '主讲部门'=>$array['department'],
                            '预算'=>$array['budget'],
                            '培训对象'=>$array['trainingObject'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}','{{name}}'],[$this->control['name'],$info['name']],L('trainingPlan.table.export_text'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, str_replace(['{{name}}'],[$info['name']],L('trainingPlan.table.export_name')).".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => L('recruitment.table.commitAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '培训计划',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => L('recruitment.table.audit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => L('recruitment.table.addAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('recruitment.table.transmit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => L('recruitment.table.cancel'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('trainingPlan.table.no_plan');
        } else {
            $audit = query('audit', " targetId = '$info[id]'");
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $mxButton = '';//招聘目标按钮
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('recruitment.table.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
                //按钮
                $button[] = [
                    "name" => L('recruitment.table.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];
                $mxButton = "<span class='smallButton' onclick=\"layer('" . self::page . "','addMx',{id:'" . self::getId() . "',mainId:'" . $info['id'] . "'})\">".L('job.model.edit')."</span>\n
                             <span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delMx'})\">".L('staffProfiles.button.del')."</span>\n";
            }
            if ($this->power(self::page, 'import')) {
                $mxButton .="<span class='smallButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."',importFun:'import'})\">导入</span>\n";
            }
            if ($this->power(self::page, 'export')) {
                $mxButton .="<span class='smallButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',checkbox:'mxId[]'})\">导出</span>";
            }
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);

            $_SESSION[self::page]['id'] = $info['id'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time asc"));
            $checkAll = $this->checkAll("detailForm", "mxId");
            $tr[] = [$checkAll, L('trainingPlan.table.trainingType'), L('trainingPlan.table.trainingProject'), L('trainingPlan.table.trainingTime'), L('trainingPlan.table.hours').'(h)', L('trainingPlan.table.speakerDept'), L('trainingPlan.table.budget').'(' . static::$unit . ')', L('trainingPlan.table.trainMember')];
            $total = ['hour'=>0,'budget'=>0];
            foreach ($result['array'] as $array) {
                //列表控件
                $dominate = array(
                    "box" => array("name" => "mxId", "value" => $array['id']),
                    'edit' => array('title' => L('recruitment.table.edit'), 'click' => "layer('" . self::page . "','addMx',{id:'" . $array['id'] . "',mainId:'" . $info['id'] . "'})")
                );
                $tr[] = [$this->dominate($dominate), $array['type'], $array['project'], $array['trainingTime'], $array['hour'], $array['department'], $array['budget'], $array['trainingObject']];
                $total['hour'] += $array['hour'];
                $total['budget'] += $array['budget'];
            }
            $total_tr = [
                4=>$total['hour'],
                6=>$total['budget'],
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        L('recruitment.table.orderNo') => $info['orderNo'],
                        L('trainingPlan.table.planName') => $info['name'],
                        L('trainingPlan.table.planStartAndEnd') => $info['startDate'] . ' ~ ' . $info['endDate'],
                        L('recruitment.table.staffDept') => $info['deptName'],
                    ),
                    array(
                        L('recruitment.table.prepared') => self::findStaff($info['stid']),
                        L('department.table.creatTime') => $info['time'],
                        L('recruitment.table.commitTime') => self::null($audit['commitTime']),
                        L('trainingPlan.table.state') => $info['state'],
                    ),
                    array(
                        L('trainingPlan.table.text') => pre($info['text']),
                    ),
                ),

            ));
            $data['html'] .= $this->detailList([
                'title' => L('trainingPlan.table.planMx'),
                'button' => $mxButton,
                'html' => "
                <div class='purchaseMx'>
                    <form name='detailForm'>" .
                        hidden(array('name' => 'id', 'value' => $info['id'])) .
                        $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true, 'total' => $total_tr)) .
                    "</form>
                </div>
                ",
            ]);
            $data['html'] .= $this->detailBlock([
                L('recruitment.table.flow') => auditClass::auditRecord(self::table, $info['id'])
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 新增培训计划明细
     * @return bool|string
     */
    public function addMx()
    {
        $mx = query(self::tableMx, " id = '{$this->post('id')}'");
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('trainingPlan.table.trainingType')."：" => select(array('name' => 'type', 'class' => 'select', 'value' => $mx['type'], 'option' => explode('，', para('trainingType')))),
                must . L('trainingPlan.table.trainingProject')."：" => text(array('name' => 'project', 'class' => 'text', 'value' => $mx['project']))
            ),
            array(
                must . L('trainingPlan.table.trainingTime')."：" => text(array('name' => 'trainingTime', 'laydate' => ['type'=>'datetime'], 'value' => $mx['trainingTime'])),
                must . L('trainingPlan.table.hours')."：" => text(array('name' => 'hour', 'type' => 'number', 'unit' => '小时', 'value' => $mx['hour']))
            ),
            array(
                L('trainingPlan.table.speakerDept')."：" => text(array('name' => 'department', 'class' => 'text', 'value' => $mx['department'])),
                L('trainingPlan.table.budget')."：" => text(array('name' => 'budget', 'type' => 'number', 'unit' =>  static::$unit , 'value' => $mx['budget']))
            ),
            array(
                L('trainingPlan.table.trainMember')."：" => text(array('name' => 'trainingObject', 'class' => 'text', 'value' => $mx['trainingObject']))
            )
        ),
            'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId')))
        ));
        //返回
        return $this->layer(array("title" => L('trainingPlan.table.recordMx'), "height" => 400, "html" => $html));
    }

    /**
     * 培训计划明细编辑
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'type' => $this->post('type'),
            'project' => $this->post('project'),
            'trainingTime' => $this->post('trainingTime'),
            'hour' => $this->post('hour'),
            'budget' => $this->post('budget'),
            'department' => $this->post('department'),
            'trainingObject' => $this->post('trainingObject'),
        ];
        $annotation = [
            'type' => L('trainingPlan.table.trainingType'),
            'project' => L('trainingPlan.table.trainingProject'),
            'trainingTime' => L('trainingPlan.table.trainingTime'),
            'hour' => L('trainingPlan.table.hours'),
            'budget' => L('trainingPlan.table.budget'),
        ];
        $rules = [
            'type' => 'required',
            'project' => 'required',
            'trainingTime' => 'required|date',
            'hour' => 'required|numeric',
            'budget' => 'numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        $info = query(self::table, " id = '" . $this->post('mainId') . "' ");
        $infoMx = query(self::tableMx, " id = '" . $id . "' ");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('trainingPlan.table.edit_permission');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('trainingPlan.table.no_plan');
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            if (empty($infoMx['id'])) {
                $field = array_merge(
                    $field,
                    [
                        'id' => $id,
                        'orderId' => $info['id'],
                        'time' => $this->time,
                    ]
                );
                $json['warn'] = static::insert(array(
                    "table" => self::tableMx,
                    "field" => $field,
                ));
            } else {
                //更新员工档案
                $json['warn'] = update(array(
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => "id = '$infoMx[id]'",
                ));
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{name}}','{{id}}'],[$this->control['name'],$field['project'],$id],L('trainingPlan.table.planMx_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        //返回
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'delMx':
                $act = 'del';
                $msg = L('trainingPlan.table.delMx');
                $title = self::page . 'DeleteMx';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = L('trainingPlan.table.delPlan');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('recruitment.table.msg'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('recruitment.table.del_per');
        } elseif (empty($array)) {
            $json['warn'] = L('recruitment.table.no_data');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = L('recruitment.table.draft');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('recruitment.table.del_suc');
                    $x++;
                }
                $text .= str_replace(['{{name}}', '{{orderNo}}', '{{id}}'], [$info['name'], $info['orderNo'], $info['id']], L('trainingPlan.table.plan_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('trainingPlan.table.plan_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('trainingPlan.table.plan_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除培训明细
     * @return bool|string
     */
    public function deleteMx()
    {
        $array = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('recruitment.table.del_per');
        } elseif (empty($array)) {
            $json['warn'] = L('recruitment.table.no_data');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                $info = query(self::table, " id = '$mx[orderId]' ");
                if ($info['state'] != '草稿') {
                    $warn = L('recruitment.table.draft');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                    //返回
                    $warn = L('recruitment.table.del_suc');
                    $x++;
                }
                $text .= str_replace(['{{type}}', '{{project}}', '{{id}}'], [$mx['type'], $mx['project'], $mx['id']], L('trainingPlan.table.planMx_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('trainingPlan.table.planMx_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('trainingPlan.table.planMx_del_warn'));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '您还没有导入的权限';
        } else {
            $exampleData[] = [];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '培训类别'=>$example[0],
                            '培训项目'=>$example[1],
                            '培训时间'=>$example[2],
                            '培训课时'=>$example[3],
                            '主讲部门'=>$example[4],
                            '预算'=>$example[5],
                            '培训对象'=>$example[6],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = $this->control['name']."导出了".self::title.'导入模板-'.$importTemplate['name'].'.xlsx';
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'培训类别',
                    'aliasName'=>'培训类别',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'培训项目',
                    'aliasName'=>'培训项目',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'培训时间',
                    'aliasName'=>'培训时间',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'培训课时',
                    'aliasName'=>'培训课时(h)',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'主讲部门',
                    'aliasName'=>'主讲部门',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'预算',
                    'aliasName'=>'预算(元)',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'培训对象',
                    'aliasName'=>'培训对象',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'培训类别',
                    'aliasName'=>'培训类别',
                ],
                [
                    'columnName'=>'培训项目',
                    'aliasName'=>'培训项目',
                ],
                [
                    'columnName'=>'培训时间',
                    'aliasName'=>'培训时间',
                ],
                [
                    'columnName'=>'培训课时',
                    'aliasName'=>'培训课时(h)',
                ],
                [
                    'columnName'=>'主讲部门',
                    'aliasName'=>'主讲部门',
                ],
                [
                    'columnName'=>'预算',
                    'aliasName'=>'预算',
                ],
                [
                    'columnName'=>'培训对象',
                    'aliasName'=>'培训对象',
                ],
            ]
        };
    }
}

